//
//  BudgetCardView.swift
//  Speek
//
//  Created by MikeHo on 2023/6/26.
//

import SwiftUI
import CoreData

struct BudgetCardView: View {
    
    @Binding var budget : BudgetDetail
    let year : String
    let month : String
    @State private var totalExpense : Double = 0.0
    @State private var bill : [BillDetail] = []
    @State private var percentageShow : Double = 0.0
    @State private var isBudgetNotSet = false
    @State private var isOutOfBudget = false

    @Environment(\.managedObjectContext) private var context
    
    var body: some View {
        
        ZStack{
            VStack{
                //各类别预算图片、标题和日期
                HStack{
                    //各类别预算的名称/消费次数/预算总数
                    Text(budget.type ?? "")
                        .bold()
                        .font(.title2)
                    Text("\(bill.count)笔支出")
                        .font(.body)
                    Spacer()
                    Text("¥\(String(format: "%.2f", budget.amount))")
                        .bold()
                        .font(.title2)
                        .foregroundStyle(
                            LinearGradient(
                                gradient: Gradient(colors: [Color(red:1,green: 0.420,blue: 0.349), Color(red:0.647,green: 0.839,blue: 0.247)]),
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                }
                .padding(.vertical,20)
                
                //各类别预算使用情况
                if isBudgetNotSet{
                    HStack{
                        Text("未设置")
                            .padding(.leading,10)
                        Spacer()
                    }
                    .bold()
                    .font(.body)
                    
                }else{
                    //超支样式
                    if isOutOfBudget{
                        HStack{
                            Text("超支")
                            Text("¥\(String(format: "%.2f",totalExpense - budget.amount ))")
                            Spacer()
                            //计算百分比
                            Text((String(format: "%.2f",(totalExpense - budget.amount)/budget.amount*100))+"%")
                                .foregroundColor(Color(red: 0.831, green: 0.188, blue: 0.188))
                        }
                        .bold()
                        .font(.body)
                        
                        ProgressView(value: percentageShow, total: 1.0)
                            .accentColor(Color(red: 0.831, green: 0.188, blue: 0.188)) // 设置进度条颜色
                            .frame(height: 10) // 设置进度条高度
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                        
                    }else{
                        //剩余样式
                        HStack{
                            Text("剩余")
                            Text("¥\(String(format: "%.2f",budget.amount - totalExpense))")
                            Spacer()
                            //计算百分比
                            Text("\(String(format: "%.2f",(percentageShow * 100)))%")
                                .foregroundColor(Color(red: 0.596, green: 0.847, blue: 0.741))

                        }
                        .bold()
                        .font(.body)
                        
                        ProgressView(value: percentageShow, total: 1.0)
                            .accentColor(Color(red: 0.596, green: 0.847, blue: 0.741)) // 设置进度条颜色
                            .frame(height: 10) // 设置进度条高度
                            .rotationEffect(.radians(.pi))
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                    }
                }
                
                
                Spacer()
                    
            }
            .padding(.leading,35)
            .padding(.trailing,20)
            .preferredColorScheme(.dark)
            .background(Color(red:0.04,green: 0.09,blue: 0.16).cornerRadius(30))
            .frame(width: 330,height: 130)
            .offset(x:10)
            .onAppear{
                //获取与预算日期、类型相同的账单数组
                bill = getBillDetails(year: year, month: month, type: budget.type ?? "", tag: false)
                totalExpense = calculateTotalAmount(bills: bill)
                percentageShow = getProgressPercentage()
            }
            
            Image(budget.type ?? "")
                .padding(2)
                .background(Color.white.cornerRadius(20))
                .offset(x:-155)
        }
        .onAppear{
            if (budget.amount == 0){
                isBudgetNotSet = true
            }
            if (budget.amount - totalExpense < 0) {
                isOutOfBudget = true
            }
        }
        .onChange(of: budget.amount, perform: { _ in
            if (budget.amount == 0){
                isBudgetNotSet = true
            }else{
                isBudgetNotSet = false
            }
            if (budget.amount - totalExpense < 0) {
                isOutOfBudget = true
            }else{
                isOutOfBudget = false
            }
        })
        .onChange(of: isOutOfBudget) { _ in
            percentageShow = getProgressPercentage()
        }
        
    }
    
    private func getProgressPercentage() -> Double{
        if isOutOfBudget{
            let progress = (totalExpense - budget.amount)/budget.amount
            if progress <= 1{
                return progress
            }else{
                return 1.0
            }
        }else{
            return (budget.amount-totalExpense)/budget.amount
        }
    }
        
    private func getBillDetails(year: String, month: String, type: String, tag: Bool) -> [BillDetail] {
        guard let yearInt = Int(year), let monthInt = Int(month) else {
            return []
        }
        
        let calendar = Calendar.current
        let dateComponents = DateComponents(year: yearInt, month: monthInt)
        let startDate = calendar.date(from: dateComponents)!
        let endDate = calendar.date(byAdding: .month, value: 1, to: startDate)!

        let predicates: [NSPredicate] = [
            NSPredicate(format: "date >= %@ AND date < %@ AND type == %@", startDate as NSDate, endDate as NSDate, type),
            NSPredicate(format: "tag == %@", tag as NSNumber)
        ]
        
        let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
        
        let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
        
        let fetchRequest: NSFetchRequest<BillDetail> = BillDetail.fetchRequest()
        fetchRequest.predicate = compoundPredicate
        fetchRequest.sortDescriptors = [sortDescriptor]
        
        do {
            let results = try context.fetch(fetchRequest)
            return results
        } catch {
            print("Error fetching bills: \(error)")
            return []
        }
    }

    
    //计算账单花费总和
    private func calculateTotalAmount(bills: [BillDetail]) -> Double {
        let totalAmount = bills.reduce(0.0) { $0 + ($1.cost ) }
        return totalAmount
    }


}

